package org.simpleframework.mvc.render.impl;

import org.simpleframework.mvc.RequestProcessorChain;
import org.simpleframework.mvc.render.ResultRender;
import org.simpleframework.mvc.type.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 视图渲染器
 *
 * @author: Oliver
 * @time: 2020/12/29/19:59
 */
public class ViewResultRender implements ResultRender {
    public static final String JSP_SOURCE_TEMPLATE = "/templates/";
    private ModelAndView modelAndView;

    public ViewResultRender(Object result) {
        if (result instanceof ModelAndView) {
            modelAndView = (ModelAndView) result;
        } else if (result instanceof String) {
            // 返回的是视图
            modelAndView = new ModelAndView().setView((String) result);
        } else {
            //3.针对其他情况，则直接抛出异常
            throw new RuntimeException("illegal request result type");
        }
    }

    @Override
    public void render(RequestProcessorChain chain) throws Exception {
        HttpServletResponse response = chain.getResponse();
        HttpServletRequest request = chain.getRequest();
        Map<String, Object> data = modelAndView.getData();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            request.setAttribute(entry.getKey(), entry.getValue());
        }
        request.getRequestDispatcher(JSP_SOURCE_TEMPLATE +modelAndView.getView()).forward(request, response);
    }
}
